package org.example.user;

import com.sun.deploy.util.StringUtils;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class SendMsgRunnable implements Runnable{

     boolean  running = true;
     Socket client;
     String username;
     DataOutputStream dos;
     BufferedReader br;
     public SendMsgRunnable(Socket s,String username)  {
        this.client = s;
        this.username = username;
        br = new BufferedReader(new InputStreamReader(System.in));
         try {
             dos = new DataOutputStream(client.getOutputStream());
             send(this.username);
         } catch (IOException e) {
             throw new RuntimeException(e);

         }


     }

    private void release() {
        try {
            if( dos != null )
                dos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        try {
            if( client != null )
                client.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    //从控制台获取信息
    private String fromconsole() {
        try {
            return  br.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            this.release();
        }
        return "";
    }
    //向服务端发送信息
    private void send( String msg) {
        try {
            dos.writeUTF(msg);
            dos.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            this.running = false;
            this.release();
        }
    }


    public void run() {
        // TODO Auto-generated method stub

        while(running) {
            String msg = fromconsole();
            if( !msg.equals("")) {
                send(msg);
            }
        }
    }

}
